package com.soap.desensitize.strategy.rreversible.symmetry;

import com.soap.desensitize.encry.rreversible.symmetry.AbstractSymmetryEncry;
import com.soap.desensitize.exception.strategy.EncodeException;

import java.io.UnsupportedEncodingException;

/**
 * @desc： Rc4加解密
 * @author： QGP
 * @create： 2022/4/23 18:08
 */

public class Rc4Strategy extends AbstractSymmetryEncry<String> {
    private static Rc4Strategy instance = null;

    /**
     * @return
     * @desc 获得实例
     */
    public static synchronized Rc4Strategy getInstance() {
        if (instance == null) {
            instance = new Rc4Strategy();
        }
        return instance;
    }

    /**
     * 密钥算法
     */
    private static final String ALGORITHM = "RC4";

    /**
     * 默认编码
     */
    private static final String CHARSET = "utf-8";

    /**
     * @desc 默认使用子类加密密码
     */

    /**
     * @desc 默认使用子类加密密码
     */
    private Rc4Strategy() {
        super.password = this.password;
    }


    /**
     * @desc 使用默认加密密码，加密
     */
    @Override
    public String encode(String data) throws EncodeException {
        return encode(password, data);
    }

    /**
     * @desc 使用默认加密密码，解密
     */
    @Override
    public String decode(String data) {
        return decode(password, data);
    }


    /**
     * @desc 使用自定义密码加密
     * @param password
     * @param data
     * @return
     */
    @Override
    public String encode(String password, String data) throws EncodeException {
        if (data == null || password == null) {
            return null;
        }
        try {
            return bytesToHex(encryRC4Byte(data, password));
        } catch (UnsupportedEncodingException e) {
            throw new EncodeException("加密失败");
        }
    }

    /**
     * @desc 使用自定义密码解密
     * @param password
     * @param data
     * @return
     */
    @Override
    public String decode(String password, String data) {
        if (data == null || password == null) {
            return null;
        }
        return new String(RC4Base(hexToByte(data), password));

    }

    /**
     * @desc  RC4加密，将加密后的字节数据
     * @param data 需要加密的数据
     * @param key  加密密钥
     * @return 返回加密后的数据
     * @throws UnsupportedEncodingException
     */
    public static byte[] encryRC4Byte(String data, String key) throws UnsupportedEncodingException {
        if (data == null || key == null) {
            return null;
        }
        byte bData[] = data.getBytes(CHARSET);
        return RC4Base(bData, key);
    }


    /**
     * RC4加密初始化密钥
     *
     * @param aKey
     * @return
     */
    private static byte[] initKey(String aKey) {
        byte[] bkey = aKey.getBytes();
        byte state[] = new byte[256];

        for (int i = 0; i < 256; i++) {
            state[i] = (byte) i;
        }
        int index1 = 0;
        int index2 = 0;
        if (bkey.length == 0) {
            return null;
        }
        for (int i = 0; i < 256; i++) {
            index2 = ((bkey[index1] & 0xff) + (state[i] & 0xff) + index2) & 0xff;
            byte tmp = state[i];
            state[i] = state[index2];
            state[index2] = tmp;
            index1 = (index1 + 1) % bkey.length;
        }
        return state;
    }


    /**
     * @desc  字节数组转十六进制
     * @param bytes
     * @return
     */
    public static String bytesToHex(byte[] bytes) {
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < bytes.length; i++) {
            String hex = Integer.toHexString(bytes[i] & 0xFF);
            if (hex.length() < 2) {
                sb.append(0);
            }
            sb.append(hex);
        }
        return sb.toString();
    }

    /**
     * @desc  十六进制转字节数组
     * @param inHex
     * @return
     */
    public static byte[] hexToByte(String inHex) {
        int hexlen = inHex.length();
        byte[] result;
        if (hexlen % 2 == 1) {
            hexlen++;
            result = new byte[(hexlen / 2)];
            inHex = "0" + inHex;
        } else {
            result = new byte[(hexlen / 2)];
        }
        int j = 0;
        for (int i = 0; i < hexlen; i += 2) {
            result[j] = (byte) Integer.parseInt(inHex.substring(i, i + 2), 16);
            j++;
        }
        return result;
    }

    /**
     * @desc  RC4解密
     * @param input
     * @param mKkey
     * @return
     */
    private static byte[] RC4Base(byte[] input, String mKkey) {
        int x = 0;
        int y = 0;
        byte key[] = initKey(mKkey);
        int xorIndex;
        byte[] result = new byte[input.length];
        for (int i = 0; i < input.length; i++) {
            x = (x + 1) & 0xff;
            y = ((key[x] & 0xff) + y) & 0xff;
            byte tmp = key[x];
            key[x] = key[y];
            key[y] = tmp;
            xorIndex = ((key[x] & 0xff) + (key[y] & 0xff)) & 0xff;
            result[i] = (byte) (input[i] ^ key[xorIndex]);
        }
        return result;
    }
}